<template>
  <a-drawer
      :title="editId || editId == 0 ? '编辑招商计划' : '新建招商计划'"
      :maskClosable="true"
      :visible="visible"
      :width="$store.getters.isMobile ? 350 : 600"
      :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
      @close="onCancel"
  >
    <a-form layout="vertical">
      <a-row :gutter="[12, 12]" :wrap="true">
        <a-col :span="24">
          <a-form-item label="计划标题" v-bind="validateInfos.name">
            <a-input
                class="w-100p"
                placeholder="请输入计划标题"
                v-model:value="modelRef.name"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="计划任务描述" v-bind="validateInfos.desc">
            <a-textarea
                placeholder="请输入计划任务描述"
                :auto-size="{ minRows: 3 }"
                v-model:value="modelRef.desc"
                showCount
                :maxlength="200"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="目标类型" v-bind="validateInfos.target_type">
            <a-select
                class="w-100p"
                v-model:value="modelRef.target_type"
                placeholder="请选择目标类型"
                allowClear
                :options="typeList"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item :label="modelRef.target_type == 4 ? '目标金额' : '目标数量'"
                       v-bind="validateInfos.target_num">
            <a-input-number
                class="w-100p"
                :placeholder="`请输入目标${modelRef.target_type == 4 ? '金额' : '数量'}`"
                :min="1"
                :precision="0"
                v-model:value="modelRef.target_num"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="执行周期类型" v-bind="validateInfos.execute_cycle">
            <a-radio-group v-model:value="modelRef.execute_cycle" :options="timeTypeOptions"
                           @change="handleChangeExecute"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="执行时间" v-bind="validateInfos.plan_time">
            <a-range-picker
                class="w-100p"
                v-if="selectTimePicker !== 'quarter'"
                :picker="selectTimePicker"
                :value="modelRef.plan_time"
                @change="handleRangePickerChange"
            >
              <template #suffixIcon>
                <CalendarOutlined/>
              </template>
            </a-range-picker>
            <a-range-picker
                v-else
                class="w-100p"
                :picker="selectTimePicker"
                :value="modelRef.plan_time"
                :format="customerFormat"
                @change="handleRangePickerChange"
            >
              <template #suffixIcon>
                <CalendarOutlined/>
              </template>
            </a-range-picker>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="执行人员" v-bind="validateInfos.execute_uids_show">

            <a-cascader
                style="margin-top: 10px"
                v-model:value="modelRef.execute_uids_show"
                :options="groupOptions"
                :load-data="getTeamList"
                placeholder="请选择执行人员"
                multiple
                @change="changeExecuteUid"
            />

          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="状态" v-bind="validateInfos.status">
            <div class="status-box">
              <div
                  v-for="(item, index) of statusList"
                  :key="index"
                  class="status-item"
                  :class="modelRef.status === item.value ? 'active' : ''"
                  @click="modelRef.status = item.value"
              >
                {{ item.label }}
              </div>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-footer">
      <a-space>
        <a-button @click.prevent="onCancel">取消</a-button>
        <a-button type="primary" @click.prevent="onSubmit" :loading="loading">确定</a-button>
      </a-space>
    </div>


  </a-drawer>
</template>

<script>
import {defineComponent, reactive, watch, toRefs, computed, ref} from "vue";
import request from "../../../../common/utils/request";
import {Form, message} from "ant-design-vue";
import {
  CalendarOutlined,
  UserOutlined,
  PartitionOutlined,
} from "@ant-design/icons-vue";

const useForm = Form.useForm;
import _ from "lodash";
import moment from "moment";
import {PLAN_TYPE_OPTIONS} from "@/views/village/AttractPlan/constant";

export default defineComponent({
  name: "AddPlan",
  components: {
    CalendarOutlined,
    UserOutlined,
    PartitionOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [Number, String, undefined],
      default: undefined,
    },
  },
  setup(props, context) {
    const state = reactive({
      typeList: PLAN_TYPE_OPTIONS,
      statusList: STATUS_OPTIONS,
      execute_uids_show: [],
      timeTypeOptions: TIME_TYPE_OPTIONS,
      loading: false,
    });

    const modelRef = reactive({
      name: "",
      desc: "",
      target_type: undefined,
      target_num: undefined,
      plan_start: undefined,
      plan_end: undefined,
      plan_time: undefined,
      execute_uids: [],
      status: 1,
      execute_cycle: 1, // 默认年 兼容老数据 没有的话就是日
    });
    const ruleRef = reactive({
      name: [{required: true, message: "必填项"}],
      desc: [{required: true, message: "必填项"}],
      target_type: [{required: true, message: "必选项"}],
      target_num: [{required: true, message: "必填项"}],
      plan_time: [{required: true, message: "必填项"}],
      execute_uids_show: [{required: true, message: "必选项"}],
    });

    const {resetFields, validate, validateInfos} = useForm(modelRef, ruleRef);

    const onCancel = () => {
      context.emit("cancel");
    };


    const handleRangePickerChange = (date, dateString) => {
      modelRef.plan_time = date;
    };

    const onSubmit = () => {
      validate().then(() => {
        state.loading = true
        if (selectTimePicker.value == "year") {
          // 年
          modelRef.plan_start = modelRef.plan_time[0].startOf('year').format("YYYY-MM-DD");
          modelRef.plan_end = modelRef.plan_time[1].endOf('year').format("YYYY-MM-DD");
        } else if (selectTimePicker.value == "quarter") {
          modelRef.plan_start = modelRef.plan_time[0].format("YYYY-MM-DD");
          modelRef.plan_end = modelRef.plan_time[1].add(2, 'month').endOf('month').format("YYYY-MM-DD");
        } else if (selectTimePicker.value == "month") {
          modelRef.plan_start = modelRef.plan_time[0].startOf('month').format("YYYY-MM-DD");
          modelRef.plan_end = modelRef.plan_time[1].endOf('month').format("YYYY-MM-DD");
        } else if (selectTimePicker.value == "week") {
          modelRef.plan_start = modelRef.plan_time[0].startOf('week').format("YYYY-MM-DD");
          modelRef.plan_end = modelRef.plan_time[1].endOf('week').format("YYYY-MM-DD");
        } else {
          modelRef.plan_start = modelRef.plan_time[0].format("YYYY-MM-DD");
          modelRef.plan_end = modelRef.plan_time[1].format("YYYY-MM-DD");
        }

        let params = _.cloneDeep(modelRef);
        delete params.plan_time;
        params.execute_uids_show = state.execute_uids_show;
        if (props.editId || props.editId == 0) {
          // 编辑
          request
              .put("/org", "/business/plan/edit", {
                ...params,
                id: props.editId,
              })
              .then((res) => {
                state.loading = false
                message.success(res.msg || "保存成功！");
                context.emit("success");
              });
        } else {
          // 新增
          request
              .post("/org", "/business/plan/add", {
                ...params,
              })
              .then((res) => {
                state.loading = false
                message.success(res.msg || "保存成功！");
                context.emit("success");
              });
        }
      });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    const getDetail = () => {
      const params = {
        id: props.editId,
        page: 1,
        limit: 10,
      };
      request.get("/org", "/business/plan/detail", params).then((res) => {
        const detail = res.planDetail || {};
        setModelRef({
          name: detail.name,
          desc: detail.desc,
          target_type: detail.target_type,
          target_num: detail.target_num,
          plan_start: detail.plan_start,
          plan_end: detail.plan_end,
          plan_time: [moment(detail.plan_start), moment(detail.plan_end)],
          execute_uids: detail?.execute_uids || [],
          execute_uids_show: detail?.execute_uids_show || [],
          status: detail.status,
          execute_cycle: detail?.execute_cycle || 5,
        });


      });
    };


    const groupOptions = ref([]);

    const getSub = (val, isSelect) => {
      request.get("/org", "/business/customerTeam/teamUserIndex", {team_id: val.value}).then(res => {
        console.log(res)
        val.children = res.data.map(item => {
          return {
            label: item.name,
            value: item.uid
          }
        })
        groupOptions.value = [...groupOptions.value];

        const uids = []
        if (isSelect) {
          res.data.forEach(item => {
            uids.push(item.uid)
          })
        }
        modelRef.execute_uids = modelRef.execute_uids.concat(uids)
      });
    }
    const getGroupList = () => {
      request.post("/org", "/business/customerTeam/list").then(res => {
        // console.log(res)
        groupOptions.value = res.list.map(item => {
          return {
            label: item.name,
            value: item.id,
            isLeaf: false,
          }
        })

        if (props.editId) {
          groupOptions.value.forEach((item) => {
            getSub(item, false)
          })
        }

      })
    }

    const changeExecuteUid = (selectedOptions) => {

      const uids = [];
      modelRef.execute_uids = []
      selectedOptions.forEach(item => {
        if (item.length == 1) {
          //全部都选择了
          console.log(item[0], "aaaa")
          console.log(groupOptions.value, "aaaa")
          let group = undefined
          groupOptions.value.forEach(groupItem => {
            if (groupItem.value == item[0]) {
              group = groupItem;
            }
          })
          if (group) {
            getSub(group, true)
          }

        } else {
          //选择了 【第一层的value，第二层的value】
          item.forEach((subItem, index) => {
            if (index > 0) {
              uids.push(subItem)
            }
          })
        }
      })
      modelRef.execute_uids = uids
      state.execute_uids_show = selectedOptions

      console.log(selectedOptions)
      console.log(state.execute_uids_show)
    }

    const getTeamList = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      // console.log(targetOption)
      request.get("/org", "/business/customerTeam/teamUserIndex", {team_id: targetOption.value}).then(res => {
        console.log(res)
        targetOption.loading = false;
        targetOption.children = [];
        targetOption.children = res.data.map(item => {
          return {
            label: item.name,
            value: item.uid
          }
        })
        groupOptions.value = [...groupOptions.value];
      });
    }


    watch(
        () => props.visible,
        (val) => {
          if (val) {
            getGroupList()
            if (props.editId || props.editId == 0) {
              getDetail();
            }
          } else {
            resetFields();
            modelRef.execute_uids = []
            modelRef.execute_uids_show = []
          }
        }
    );

    const handleChangeExecute = () => {
      modelRef.plan_time = undefined;
    };

    const selectTimePicker = computed(() => state.timeTypeOptions.find((v) => v.value == modelRef.execute_cycle)?.picker || 'date');

    const getChineseNumber = (number) => {
      const chineseNumbers = ['一', '二', '三', '四'];
      return chineseNumbers[number - 1];
    };
    const customerFormat = (value) => {
      let data = value.format("YYYY-Q");
      if (data) {
        let dataArr = data.split('-');
        return `${dataArr[0]}-第${getChineseNumber(dataArr[1])}季度`;
      }
      return data;
    };

    return {
      modelRef,
      validateInfos,
      selectTimePicker,
      ...toRefs(state),
      onCancel,
      onSubmit,
      handleRangePickerChange,
      handleChangeExecute,
      customerFormat,
      getTeamList,
      groupOptions,
      changeExecuteUid
    };
  },
});

const STATUS_OPTIONS = [
  {
    value: 1,
    label: "启用",
  },
  {
    value: 0,
    label: "停用",
  },
];

const TIME_TYPE_OPTIONS = [
  {
    value: 1,
    label: "年",
    picker: "year",
  },
  {
    value: 2,
    label: "季",
    picker: "quarter",
  },
  {
    value: 3,
    label: "月",
    picker: "month",
  },
  {
    value: 4,
    label: "周",
    picker: "week",
  },
  {
    value: 5,
    label: "日",
    picker: "date",
  },
]
</script>

<style lang="less" scoped>
.user-tag :deep(.ant-tag) {
  border-radius: 20px !important;
  padding: 0 12px 0 0 !important;
  background: #f1f1f1;
  border: none;
}

.status-box {
  display: flex;
}

.status-item {
  padding: 5px 16px;
  border: 1px solid #d9d9d9;
  cursor: pointer;

  &:last-child {
    border-left: none;
  }
}

.active {
  background-color: @primary-color;
  color: #fff;
}
</style>
